package com.example.demo.BeanTest.util;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.beans.FeatureDescriptor;
import java.util.Arrays;


/**
 * @author LF
 * @date 2023-05-09
 */
public class CopyUtil {
    /**
     * 重写copy方法,使得新容器内null字段的值使用旧容器内的数据
     *
     * @param src 旧容器
     * @param dst 新容器
     * @return
     */
    public static <T> T copyPropertiesIgnoreNull(Object src, T dst) {
        final BeanWrapper beanWrapper = new BeanWrapperImpl(src);
        BeanUtils.copyProperties(src, dst, Arrays
                .stream(beanWrapper.getPropertyDescriptors())
                .map(FeatureDescriptor::getName)
                .filter(name -> beanWrapper.getPropertyValue(name) == null)
                .toArray(String[]::new)
        );
        return dst;
    }
}
